package interview.javabase.thread.forkjoinpool;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

import static com.study.util.LogUtil.info;

@SuppressWarnings("all")
@Slf4j
public class ForkJoinTask extends RecursiveTask<List<String>> {

    private int THRESHOLD = 2;
    private int start;
    private int end;

    public ForkJoinTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected List<String> compute() {
        List<String> list = new ArrayList<>();

        //如果任务足够小就计算任务
        if ((end - start) <= THRESHOLD) {
            for (int i = start; i < end; i++) {
                info("线程池中线程数目：" + getPool().getPoolSize() + "，队列中等待执行的任务数目：" +
                        getPool().getQueuedTaskCount());
                list.add(null);
            }
            return list;
        }

        int middle = (end + start) / 2;
        ForkJoinTask task1 = new ForkJoinTask(start, middle);
        ForkJoinTask task2 = new ForkJoinTask(middle, end);
        task1.fork();
        task2.fork();

        //等待任务执行结束合并其结果
        List<String> leftResult = task1.join();
        List<String> rightResult = task2.join();
        list.addAll(leftResult);
        list.addAll(rightResult);
        return list;
    }
}
